﻿using System;
using System.ComponentModel.Composition;
using Caliburn.Micro;

namespace PocketBook.Tasks
{
    public class OpenDialog<TDialog> : IResult where TDialog : class, IDialog
    {
        public OpenDialog(TDialog dialog)
        {
            Dialog = dialog;
        }

        public OpenDialog<TDialog> With(Action<TDialog> initialize)
        {
            initialize(Dialog);
            return this;
        }

        public TDialog Dialog { get; private set; }

#if ! WINDOWS_PHONE
        [Import]
        public IWindowManager WindowManager { get; set; }
#endif

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };

        public void Execute(ActionExecutionContext context)
        {
            Dialog.Completed += OnDialogCompleted;
#if ! WINDOWS_PHONE
            var result = WindowManager.ShowDialog(Dialog, null);
#endif
            Completed(this, new ResultCompletionEventArgs { WasCancelled = result != true });
        }

        private void OnDialogCompleted(object sender, DialogResultCompletionEventArgs e)
        {
            var screen = sender as IScreen;
            if (screen == null) throw new ArgumentException("sender");

            screen.CanClose(delegate(bool a) { if (!a) return; });
            screen.TryClose();

            Dialog.Completed -= OnDialogCompleted;

            var args = new ResultCompletionEventArgs
                       {
                           WasCancelled = !(e.DialogResult.HasValue && e.DialogResult.Value),
                           Error = e.Error
                       };

            Completed(this, args);
        }
    }
}